<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="追溯类型" prop="traceType">
        <el-select v-model="queryParams.traceType" placeholder="请选择追溯类型" clearable>
          <el-option label="正向追溯" value="forward" />
          <el-option label="反向追溯" value="reverse" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="queryParams.startDate"
          type="date"
          placeholder="选择开始日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="queryParams.endDate"
          type="date"
          placeholder="选择结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <el-card class="box-card">
          <div class="statistic-card">
            <div class="statistic-title">总追溯次数</div>
            <div class="statistic-value">{{ analysisData.totalCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div class="statistic-card">
            <div class="statistic-title">正向追溯</div>
            <div class="statistic-value">{{ analysisData.forwardCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div class="statistic-card">
            <div class="statistic-title">反向追溯</div>
            <div class="statistic-value">{{ analysisData.reverseCount || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card">
          <div class="statistic-card">
            <div class="statistic-title">平均追溯深度</div>
            <div class="statistic-value">{{ analysisData.avgDepth || 0 }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>追溯类型分布</span>
          </div>
          <div id="traceTypeChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>追溯趋势图</span>
          </div>
          <div id="traceTrendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 追溯记录列表 -->
    <el-card class="box-card" style="margin-top: 20px;">
      <div slot="header" class="clearfix">
        <span>追溯记录详情</span>
      </div>
      <el-table v-loading="loading" :data="analysisData.records">
        <el-table-column label="追溯编码" align="center" prop="traceCode" />
        <el-table-column label="追溯类型" align="center" prop="traceType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_trace_type" :value="scope.row.traceType"/>
          </template>
        </el-table-column>
        <el-table-column label="对象类型" align="center" prop="objectType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.mes_object_type" :value="scope.row.objectType"/>
          </template>
        </el-table-column>
        <el-table-column label="工单编号" align="center" prop="workOrderCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="追溯深度" align="center" prop="traceDepth" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getTraceAnalysis } from "@/api/mes/traceability/traceability"
import * as echarts from 'echarts'

export default {
  name: "TraceAnalysis",
  dicts: ['mes_trace_type', 'mes_object_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        traceType: null,
        startDate: null,
        endDate: null
      },
      // 分析数据
      analysisData: {
        totalCount: 0,
        forwardCount: 0,
        reverseCount: 0,
        avgDepth: 0,
        records: []
      }
    };
  },
  created() {
    this.getAnalysisData();
  },
  methods: {
    /** 查询分析数据 */
    getAnalysisData() {
      this.loading = true;
      getTraceAnalysis(this.queryParams).then(response => {
        this.analysisData = response.data;
        this.calculateStatistics();
        this.loading = false;
        this.$nextTick(() => {
          this.initCharts();
        });
      });
    },
    /** 计算统计数据 */
    calculateStatistics() {
      const records = this.analysisData.records || [];
      this.analysisData.totalCount = records.length;
      this.analysisData.forwardCount = records.filter(r => r.traceType === 'forward').length;
      this.analysisData.reverseCount = records.filter(r => r.traceType === 'reverse').length;
      
      if (records.length > 0) {
        const totalDepth = records.reduce((sum, r) => sum + (r.traceDepth || 0), 0);
        this.analysisData.avgDepth = (totalDepth / records.length).toFixed(1);
      }
    },
    /** 初始化图表 */
    initCharts() {
      this.initTraceTypeChart();
      this.initTraceTrendChart();
    },
    /** 初始化追溯类型分布图 */
    initTraceTypeChart() {
      const chart = echarts.init(document.getElementById('traceTypeChart'));
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '追溯类型',
            type: 'pie',
            radius: '50%',
            data: [
              { value: this.analysisData.forwardCount, name: '正向追溯' },
              { value: this.analysisData.reverseCount, name: '反向追溯' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      chart.setOption(option);
    },
    /** 初始化追溯趋势图 */
    initTraceTrendChart() {
      const chart = echarts.init(document.getElementById('traceTrendChart'));
      // 这里可以根据实际数据生成趋势图
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['追溯次数']
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '追溯次数',
            type: 'line',
            data: [12, 19, 3, 5, 2, 3, 8]
          }
        ]
      };
      chart.setOption(option);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getAnalysisData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.getAnalysisData();
    }
  }
};
</script>

<style scoped>
.statistic-card {
  text-align: center;
  padding: 20px;
}

.statistic-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.statistic-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
}

.mb20 {
  margin-bottom: 20px;
}
</style>